package com.zimmor.mq.rocket_train1.base;

import com.zimmor.mq.RocketMQProperties;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

/**
 * @Author:zimmor
 * @Date: 2023/2/16 14:46
 * @Description 发送异步消息
 * @version: 1.0.0
 */

public class AsyncProducer {
    public static void main(String[] args) throws MQClientException, RemotingException, InterruptedException {
        //创建生产者
        DefaultMQProducer producer = new DefaultMQProducer("producer-group1");
        //设置namesrv
        producer.setNamesrvAddr(RocketMQProperties.NAME_SRV_ADDR);
        //启动生产者
        producer.start();
        for (int i = 0; i < 10; i++) {
        //构建消息
            Message message = new Message("base1", "tag1", ("asyncMessage" + i).getBytes());
            //发送消息
            producer.send(message, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.println("发送成功：" + sendResult.toString());
                }

                @Override
                public void onException(Throwable throwable) {
                    System.out.println("发送失败！");
                    throwable.printStackTrace();
                }
            });
        }
    }
}
